<template>
  <viewer
    v-show="false"
    ref="viewer"
    :options="options"
    :images="images"
    class="viewer"
    @inited="(obj) => (viewer = obj)"
  >
    <template slot-scope="scope">
      <template v-for="(item, index) in scope.images">
        <img
          v-if="$func.isObject(item)"
          :key="index"
          :src="item.thumbnail"
          :data-source="item.source ? item.source : item.thumbnail"
          class="image"
          :alt="item.alt ? item.alt : item.thumbnail"
        />
        <img
          v-else
          :key="index"
          :src="item"
          :data-source="item"
          class="image"
          :alt="item"
        />
      </template>
    </template>
  </viewer>
</template>

<script>
export default {
  model: {
    //event:什么时候触发v-model行为
    event: "change-visible",
    // 定义传递给v-model的那个变量，绑定到哪个属性值上
    prop: "visible",
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    data: {
      type: [String, Array, Object],
      default: () => {
        return null
      },
    },
    where: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      viewer: undefined,
      options: {
        toolbar: true,
        navbar: true,
        movable: false,
        url: "data-source",
      },
      images: [],
    }
  },
  computed: {
    objId() {
      if (this.$func.isArray(this.data) || this.$func.isObject(this.data)) {
        return JSON.stringify(this.data)
      } else {
        return this.data
      }
    },
    hiding() {
      if (this.visible) {
        return !this.viewer ? true : this.viewer.hiding
      }
      return true
    },
  },
  watch: {
    visible(showFlag) {
      if (showFlag) this.show()
    },
    hiding(flag) {
      this.$emit("change-visible", !flag)
    },
    objId() {
      this.initData()
    },
  },
  mounted() {
    this.initData()
  },
  methods: {
    initData() {
      this.images = Array.isArray(this.data)
        ? this.data.length > 0
          ? this.data
          : []
        : this.$func.isObject(this.data)
        ? [this.data]
        : this.data !== ""
        ? [this.data]
        : []

      this.options.navbar = this.images.length <= 1 ? false : true
    },
    show() {
      this.viewer.show()
    },
  },
}
</script>

<style lang="less" scoped>
.image {
  width: calc(20% - 10px);
  cursor: pointer;
  margin: 5px;
  display: inline-block;
}
</style>
